<template>
    <div class="home">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="标题">
                <el-input
                    v-model="formInline.detail"
                    clearable
                    placeholder="请输入要搜索的内容"
                    @keyup.enter.native="getList"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getList">查询</el-button>
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <el-button type="warning" @click="handleDelete">删除</el-button>
            </el-form-item>
        </el-form>
        <el-card class="box-card">
            <el-table
                v-loading="loading"
                ref="multipleTable"
                :data="tableData"
                :height="tabHeight"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="title" label="标题"> </el-table-column>
                <el-table-column prop="content" label="内容" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="create_time" :formatter="formatterDate" label="创建时间">
                </el-table-column>
                <el-table-column prop="delete_time" label="删除时间"> </el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                    <template slot-scope="scope">
                        <el-button @click="handleEdit(scope.row)" type="text">编辑</el-button>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="type" label="新闻类别"> </el-table-column> -->
            </el-table>
            <el-pagination
                @current-change="handleCurrentChange"
                :page-size="pageSiZe"
                layout="total, prev, pager, next"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <!-- 新增 -->
        <el-dialog
            :title="dialogType === 'add' ? '新增' : '编辑'"
            :visible.sync="addDialogVisible"
            width="60%"
            center
            @close="dialogClose"
        >
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
            >
                <el-form-item label="标题" prop="title">
                    <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="新闻类别" prop="type">
                    <el-select v-model="ruleForm.type" placeholder="请选择新闻类别">
                        <el-option label="行业资讯" value="0"></el-option>
                        <el-option label="公司新闻" value="15"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="create_time" label="创建时间">
                    <!-- {{ ruleForm.create_time }} -->
                    <el-date-picker
                        type="date"
                        placeholder="选择日期"
                        value-format="timestamp"
                        v-model="ruleForm.create_time"
                        style="width: 100%;"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item prop="delete_time" label="删除时间">
                    <el-date-picker
                        type="date"
                        placeholder="选择日期"
                        value-format="timestamp"
                        v-model="ruleForm.delete_time"
                        style="width: 100%;"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input
                        type="textarea"
                        v-model="ruleForm.content"
                        placeholder="请输入内容"
                    ></el-input>
                </el-form-item>
                <!-- <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">新增</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item> -->
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="addDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// @ is an alias to /src
import { formatDate1 } from '@/utils';
export default {
    name: 'Home',
    data() {
        return {
            tableData: [],
            currentPage1: 1,
            total: 0,
            curPage: 1,
            pageSiZe: 15,
            formInline: {
                detail: '',
            },
            addDialogVisible: false,
            ruleForm: {
                title: '',
                type: '',
                create_time: '',
                delete_time: '',
                content: '',
            },
            // 校验规则,和prop要相对应
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
                ],
                type: [{ required: true, message: '请选择活动区域', trigger: 'change' }],
                create_time: [{ required: true, message: '请选择日期', trigger: 'change' }],
                delete_time: [{ required: true, message: '请选择时间', trigger: 'change' }],
                content: [{ required: true, message: '请填写内容', trigger: 'blur' }],
            },
            loading: false,
            // tabTitle: '新增',
            dialogType: 'add',
            sels: [],
            tabHeight: window.innerHeight - 200,
        };
    },
    watch: {
        formInline: {
            handler(val) {
                console.log(val);
                if (!val.detail) {
                    this.getList();
                }
            },
            deep: true,
        },
    },
    methods: {
        handleEdit(row) {
            console.log(row);
            this.addDialogVisible = true;
            this.dialogType = 'edit';
            for (const key in row) {
                if (Object.hasOwnProperty.call(row, key)) {
                    if (key === 'create_time' || key === 'delete_time') {
                        row[key] = row[key] * 1000;
                    } else if (key === 'type') {
                        // row[key] = row[key] + '';
                        // row[key] = row[key].toString();
                        row[key] = String(row[key]);
                    }
                }
            }
            this.ruleForm = row;

            console.log(row);
        },
        // dialog关闭时候触发这个方法
        dialogClose() {
            this.ruleForm = {
                title: '',
                type: '',
                create_time: '',
                delete_time: '',
                content: '',
            };
        },
        submitForm() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (this.dialogType === 'add') {
                        let ruleForm = {};
                        ruleForm = JSON.parse(JSON.stringify(this.ruleForm));
                        for (const key in ruleForm) {
                            if (Object.hasOwnProperty.call(ruleForm, key)) {
                                if (key === 'create_time' || key === 'delete_time') {
                                    // ruleForm[key] = ruleForm[key].toString().substr(0, 10);
                                    ruleForm[key] = ruleForm[key] / 1000;
                                }
                            }
                        }
                        this.$http
                            .post('/api/api/news/save', {
                                ...ruleForm,
                            })
                            .then((res) => {
                                if (res.data.code === 0) {
                                    this.getList();
                                    this.addDialogVisible = false;
                                }
                            });
                    } else if (this.dialogType === 'edit') {
                        this.$http
                            .post('/api/api/news/update', { ...this.ruleForm })
                            .then((res) => {
                                if (res.data.code === 0) {
                                    console.log(this);
                                    this.$message.success('修改成功');
                                    this.getList();
                                    this.addDialogVisible = false;
                                }
                            });
                        // console.log(this.ruleForm);
                        // console.log('编辑请求接口');
                    }
                }
            });
        },
        resetForm(formName) {
            console.log('resetForm');
            // this.$refs[formName].resetFields();
        },
        // 删除
        handleDelete() {
            let arr = [];
            if (!this.sels.length) {
                this.$message.warning('请至少选择一条数据!');
                return false;
            }
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                console.log('wangjin');
                for (const key in this.sels) {
                    let { id } = this.sels[key];
                    arr.push(id);
                }
                // this.$http.post('/api/news/delete', { id: arr });
            });
            // .catch(() => {
            //     this.$message({
            //         type: 'info',
            //         message: '已取消删除',
            //     });
            // });
        },
        // 打开新增弹窗
        handleAdd() {
            this.dialogType = 'add';
            this.addDialogVisible = true;
            this.$nextTick(() => {
                this.$refs['ruleForm'].clearValidate();
            });
        },
        // 搜索时候
        onSubmit() {
            console.log('onSubmit');
            this.loading = true;
            let params = {
                title: this.formInline.detail,
            };
            this.$http
                .get('/api/api/news/index', {
                    params,
                })
                .then((response) => {
                    // console.log(response);
                    this.loading = false;
                    this.tableData = response.data.newsList;
                    this.total = response.data.count;
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        handleCurrentChange(page) {
            this.curPage = page;
            this.getList();
            // console.log('page', page);
        },
        handleSelectionChange(sel) {
            this.sels = sel;
            console.log(sel);
        },
        formatterDate(row, column, cellValue, index) {
            return formatDate1(new Date(cellValue * 1000), 'yyyy-MM-dd');
        },
        getList() {
            let params = {
                page: this.curPage,
                limit: this.pageSiZe,
                title: this.formInline.detail,
            };
            this.loading = true;
            this.$http
                .get('/api/api/news/index', {
                    params: params,
                })
                .then((response) => {
                    console.log(response);
                    this.loading = false;
                    this.tableData = response.data.newsList;
                    this.total = response.data.count;
                    // console.log(response.data.newsList);
                })
                .catch(() => {
                    this.loading = false;
                });

            // this.$http.post('http://macio.ncyateng.com/api/news/index', {}).then((response) => {
            //     console.log(response, '=======post======');
            // });
        },
    },

    created() {
        // console.log(this.$http);
        this.getList();
    },
};
</script>

<style lang="scss" scoped>
.el-select {
    display: block;
}
</style>
